package com.fausto.learnimprint.mail

import cn.hutool.core.util.RandomUtil
import com.fausto.learnimprint.message.MqConstant
import org.springframework.amqp.rabbit.core.RabbitTemplate
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit

@Service
class MailService {

    @Autowired
    lateinit var redisTemplate: RedisTemplate<String, String>

    @Autowired
    lateinit var rabbitTemplate: RabbitTemplate
    /**
     * 从redis中提取 验证码
     *
     * @param mail 邮箱
     * @return 验证码
     */
    fun getMailCodeFromRedis(mail: String): String? {
        return redisTemplate.opsForValue().get(MailConstant.REDIS_MAIL_KEY_PREFIX + mail)
    }

    /**
     * 将 邮件 和 验证码发送到消息队列
     *
     * @param mail
     */
    fun sendMail(mail: String){
        val random: Int = RandomUtil.randomInt(100000, 999999)    //邮箱验证码
        val map: MutableMap<String, String> = HashMap(2)
        val code = random.toString()
        map["mail"] = mail
        map["code"] = code

        //存入消息队列
        rabbitTemplate.convertAndSend(MqConstant.MAIL_QUEUE, map)
        //存入redis
        updateMailSendState(mail, code, MailConstant.MAIL_STATE_WAIT)
    }


    /**
     * 更改邮件发送状态
     *
     * @param mail
     * @param code
     * @param state MailConstant.MAIL_STATE_*
     */
    fun updateMailSendState(mail: String, code: String, state: Int) {
        redisTemplate.opsForValue()
            .set(
                MailConstant.REDIS_MAIL_KEY_PREFIX + mail,
                code + MailConstant.MAIL_STATE_MID_CHAR + state,
                MailConstant.EXPIRED_TIME.toLong(), TimeUnit.MINUTES
            )
    }
}